import baostock as bs
import datetime
import pandas as pd
import pymysql

# 今日推荐， 20点后使用，需使用今天的K线数据
nowTime = datetime.datetime.now().strftime('%Y-%m-%d')

db = pymysql.Connect(
    host='apiccr.megowx.com',
    port=3306,
    user='gupiao',
    passwd='Aitrip123',
    db='gupiao',
    charset='utf8'
)
cursor = db.cursor()

try:
    sql0 = "SELECT date FROM `fa_stock_k` WHERE 1 ORDER BY id DESC LIMIT 1 "
    result = cursor.execute(sql0)
    db.commit()
    if result:
        date = cursor.fetchone()
        nowTime = datetime.datetime(year=date[0].year, month=date[0].month, day=date[0].day).strftime('%Y-%m-%d')
except Exception as e:
    print(e)


# 也可自定义选股时间
# iszdy = 1
# nowTime = "2019-02-01"


# 按自定义选股时间推荐股票 => code + 1，2，3，6，10，20 交易日后涨幅
# step 1：获取绩优股   5年涨幅 > x --- 83
# SELECT code,b5,b10 FROM `fa_stock_k` where date='2019-04-30' and b10 > 5 and b5>2 ORDER BY B5 desc
#
# step 2：取最近两天的数据
# a. 反弹 --- 连续n天5日线以下, 今日上5日均线
# b. 初入新世界 --- 刚上89日均线
# c. 上升通道回踩 --- 在89日均线上，X20 接近1
# d. 海底捞 ---  X20 接近0.2?


# 大盘深跌后回暖，找跌的多的
def findA(datalist):
    global cursor
    global db

    if len(datalist) < 1:
        return False

    try:
        for i in range(0, len(datalist)):
            data = datalist[i]

            sql = "SELECT * FROM `fa_stock_k` where id<=" + str(data[0]) + " and code='" \
                  + data[2] + "' ORDER BY id desc limit 2"
            cursor.execute(sql)
            if result:
                list = cursor.fetchall()
                # 连续两天的LU5判断
                # if list[0][32] == 1 and list[1][32] < -5:
                    # print("LU5 -- " + list[0][2] + " ---  " + str(list[1][32]))

                # 上了5天线，且在89日均线上
                # if list[0][32] == 1 and list[1][36] > 10:
                #     print("LU89 -- " + list[0][2] + " ---  " + str(list[1][36]))

                # 刚上89线，且在5日均线上
                if list[0][36] == 1 and list[1][36] < -10 and list[0][32] > 0:
                    print("*LU89 -- " + list[0][2] + " ---  " + str(list[1][36]))

    except Exception as e:
        print(e)
        print(sql)

    return True


try:
    # A 反弹
    # sql = "SELECT * FROM `fa_stock_k` where date='" + nowTime + "' and b10 > 5 and b5 > 2 ORDER BY B5 desc"
    sql = "SELECT * FROM `fa_stock_k` where date='" + nowTime + "' limit 1000"
    result = cursor.execute(sql)
    if result:
        datalist = cursor.fetchall()
        findA(datalist)

    # d.海底捞
    # sql = "SELECT * FROM `fa_stock_k` where date='" + nowTime + "' and b10 > 5 and b5 > 2 ORDER BY x20 limit 10"
    # result = cursor.execute(sql)
    # if result:
    #     datalist = cursor.fetchall()
    #     for i in range(0, len(datalist)):
    #         print("DDD-- " + datalist[i][2] + " ---  " + str(datalist[i][25]))

except Exception as e:
    print(e)
    print(sql)

cursor.close()
db.close()

print('----OK---')
